<template>
  <div
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
  >
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="日期范围:" prop="startAndend">
        <el-date-picker
          v-model="queryParams.startAndend"
          type="daterange"
          size="small"
          range-separator="至"
          start-placeholder="请选择开始日期"
          end-placeholder="请选择结束日期"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="用能单位:" prop="deptId">
        <CascaderSelect
          v-model="queryParams.deptId"
          :values="queryParams.deptId"
          :varient="'energy'"
          size="small"
          placeholder="请选择用能单位"
          :filterable="true"
          @input="handlerSyschose"
        ></CascaderSelect>
      </el-form-item>
      <!-- <el-form-item prop="networksId">
        <RemoteSelect
          v-model="queryParams.networksId"
          :extraParams="extraParams"
          :varient="'networks'"
          size="small"
          placeholder="能耗终端"
          @input="choseNetwork"
        ></RemoteSelect>
      </el-form-item> -->
      <el-form-item label="设备型号:" prop="model">
        <el-select
          v-model="queryParams.model"
          placeholder="请选择设备型号"
          size="small"
        >
          <el-option
            v-for="item in dictArr"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="设备编号:" prop="deviceCode">
        <el-input
          v-model="queryParams.deviceCode"
          size="small"
          placeholder="请输入设备编号"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <!-- <el-row :gutter="20">
      <el-col :span="12">
        <pieChart :pieData="pieData1"></pieChart>
      </el-col>
      <el-col :span="12">
        <pieChart :pieData="pieData2"></pieChart>
      </el-col>
    </el-row> -->
    <!-- show-summary  -->
    <el-table :data="list" border height="640">
      <el-table-column
        prop="deptName"
        label="用能单位"
        width="160"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="networkName"
        label="监测点名称"
        width="160"
        :show-overflow-tooltip="true"
      ></el-table-column>
      <el-table-column
        prop="code"
        label="设备编号"
        :show-overflow-tooltip="true"
        width="180"
      >
      </el-table-column>
      <el-table-column
        prop="model"
        label="设备型号"
        :show-overflow-tooltip="true"
        min-width="100"
      >
      </el-table-column>
      <el-table-column label="尖峰" align="center">
        <el-table-column
          prop="spiksectionElectricity"
          label="电量（kwh）"
          width="130"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="peakPrice"
          label="单价（kwh/元）"
          width="130"
          align="center"
        >
          <!-- <template slot="header">
            <div class="flexex">
              <div>单价</div>
              <el-popover placement="top-start" title="单价" trigger="hover">
                <p>单位：元/kwh</p>
                <i slot="reference" class="el-icon-info"></i>
              </el-popover>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="peakAll"
          label="金额（元）"
          width="130"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="高峰" align="center">
        <el-table-column
          prop="peaksectionElectricity"
          label="电量（kwh）"
          width="130"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="highPrice"
          label="单价（kwh/元）"
          width="130"
          align="center"
        >
          <!-- <template slot="header">
            <div class="flexex">
              <div>单价</div>
              <el-popover placement="top-start" title="单价" trigger="hover">
                <p>单位：元/kwh</p>
                <i slot="reference" class="el-icon-info"></i>
              </el-popover>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="highAll"
          label="金额（元）"
          width="130"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="平常" align="center">
        <el-table-column
          prop="flatsectionElectricity"
          label="电量（kwh）"
          width="130"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="elPrice"
          label="单价（kwh/元）"
          width="130"
          align="center"
        >
          <!-- <template slot="header">
            <div class="flexex">
              <div>单价</div>
              <el-popover placement="top-start" title="单价" trigger="hover">
                <p>单位：元/kwh</p>
                <i slot="reference" class="el-icon-info"></i>
              </el-popover>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="elAll"
          label="金额（元）"
          width="130"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="低谷" align="center">
        <el-table-column
          prop="valleysectionElectricity"
          label="电量（kwh）"
          width="130"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="lowPrice"
          label="单价（kwh/元）"
          width="130"
          align="center"
        >
          <!-- <template slot="header">
            <div class="flexex">
              <div>单价</div>
              <el-popover placement="top-start" title="单价" trigger="hover">
                <p>单位：元/kwh</p>
                <i slot="reference" class="el-icon-info"></i>
              </el-popover>
            </div>
          </template> -->
        </el-table-column>
        <el-table-column
          prop="lowAll"
          label="金额（元）"
          width="130"
          align="center"
        >
        </el-table-column>
      </el-table-column>
      <el-table-column label="合计" align="center">
        <el-table-column
          prop="allquantity"
          label="电量（kwh）"
          width="130"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="allmoney"
          label="金额（元）"
          width="130"
          align="center"
        >
        </el-table-column>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      :page-sizes="[20, 40, 60, 80]"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { electricityList, getPieStatistices } from "@/api/iot/kwh";
// import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import pieChart from "@/views/statistics/energy/components/behaviorC/kwhPiechart.vue";
import CascaderSelect from "@/components/Select/CascaderSelect";
import RemoteSelect from "@/components/Select/RemoteSelect";
import { dealElectricity } from "@/utils/index";

export default {
  name: "kwh",
  dicts: ["device_model"],
  components: {
    pieChart,
    CascaderSelect,
    RemoteSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      list: [],
      // 部门树选项
      deptOptions: [],
      total: 0,
      // 查询参数
      queryParams: {
        startAndend: null,
        deptId: null,
        // networksId: null,
        model: null,
        deviceCode: null,
        pageNum: 1,
        pageSize: 20,
      },
      extraParams: {},
      sysDeptIdChose: null,
      dictArr: [],
      pieData1: {
        pieId: "piekwh",
        title: "电量(kwh)",
        name: "电量图",
        dataArr: [],
        totalAll: 0,
        color: ["#5087EC", "#744E20", "#F2BD42", "#58A55C"],
      },
      pieData2: {
        pieId: "pieyuan",
        title: "电费(元)",
        name: "电价图",
        dataArr: [],
        totalAll: 0,
        color: ["#377F7F", "#744E20", "#F2BD42", "#CBA43F"],
      },
    };
  },
  created() {
    this.getdeviceModel();
    // this.getPiedata();
  },
  mounted() {
    this.getList();
  },
  methods: {
    getdeviceModel() {
      this.dictArr = this.dict.type?.device_model ?? [];
    },
    getPiedata() {
      let that = this;
      let params = { ...this.queryParams };
      if (this.queryParams.startAndend) {
        params.startDate = this.queryParams.startAndend[0] ?? "";
        params.endDate = this.queryParams.startAndend[0] ?? "";
      }
      if (this.queryParams.deptId) {
        params.deptId =
          this.queryParams.deptId[this.queryParams.deptId.length - 1];
      }
      // if (this.queryParams.networksId == "") {
      //   params.networksId = null;
      // }
      params.startAndend = null;
      params.pageNum = null;
      params.pageSize = null;
      console.log(params, "echartsqqcs");
      getPieStatistices(params)
        .then((res) => {
          console.log(res, "pie");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          // 电量图
          this.pieData1.dataArr = [];
          const num1 = this.elePiedataDEal(
            res?.data?.spiksectionElectricity ?? 0,
            "尖峰"
          );
          const num2 = this.elePiedataDEal(
            res?.data?.peaksectionElectricity ?? 0,
            "高峰"
          );
          const num3 = this.elePiedataDEal(
            res?.data?.flatsectionElectricity ?? 0,
            "平常"
          );
          const num4 = this.elePiedataDEal(
            res?.data?.valleysectionElectricity ?? 0,
            "低谷"
          );
          this.pieData1.totalAll = (num1 + num2 + num3 + num4).toFixed(2);
          // 电价图
          this.pieData2.dataArr = [];
          const price1 = this.peicePiedataDEal(res?.data?.peakFee ?? 0, "尖峰");
          const price2 = this.peicePiedataDEal(res?.data?.highFee ?? 0, "高峰");
          const price3 = this.peicePiedataDEal(res?.data?.elFee ?? 0, "平常");
          const price4 = this.peicePiedataDEal(res?.data?.lowFee ?? 0, "低谷");
          this.pieData2.totalAll = dealElectricity(
            price1 + price2 + price3 + price4,
            1,
            2
          );
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!200101");
        });
    },
    elePiedataDEal(ele, name) {
      let result;
      let eleFlag = Number(dealElectricity(ele, 100, 2));
      let obj = { value: eleFlag, name: name };
      this.pieData1.dataArr.push(obj);
      result = eleFlag;
      return result;
    },
    peicePiedataDEal(price, name) {
      let result;
      let priceFlag = Number(dealElectricity(price, 100, 2));
      let obj = { value: priceFlag, name: name };
      this.pieData2.dataArr.push(obj);
      result = priceFlag;
      return result;
    },
    /** 查询部门列表 */
    getList() {
      let that = this;
      let params = { ...this.queryParams };
      if (this.queryParams.startAndend) {
        params.startDate = this.queryParams.startAndend[0] ?? "";
        params.endDate = this.queryParams.startAndend[0] ?? "";
      }
      if (this.queryParams.deptId) {
        params.deptId =
          this.queryParams.deptId[this.queryParams.deptId.length - 1];
      }
      // if (this.queryParams.networksId == "") {
      //   params.networksId = null;
      // }
      params.startAndend = null;
      console.log(params, "qqcs");
      that.$store.commit("app/updateApiCount", "add");
      electricityList(params)
        .then((res) => {
          that.$store.commit("app/updateApiCount");
          console.log(res);
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.list = res?.rows ?? [];
          that.total = res?.total ?? 0;
          that.electricityDeal();
        })
        .catch((err) => {
          that.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!200100");
        });
    },
    // 表格数据计算
    electricityDeal() {
      if (this.list.length > 0) {
        this.list.map((item) => {
          this.dictArr.map((tig) => {
            if (item.model == tig.value) {
              item.model = tig.label;
            }
          });
          // 尖峰
          item.spiksectionElectricity = dealElectricity(
            item?.spiksectionElectricity ?? 0,
            100,
            2
          );
          item.peakAll = this.priceCalculate(
            item.spiksectionElectricity,
            item.peakPrice
          );
          // 高峰
          item.peaksectionElectricity = dealElectricity(
            item?.peaksectionElectricity ?? 0,
            100,
            2
          );
          item.highAll = this.priceCalculate(
            item.peaksectionElectricity,
            item.highPrice
          );
          // 平常
          item.flatsectionElectricity = dealElectricity(
            item?.flatsectionElectricity ?? 0,
            100,
            2
          );
          item.elAll = this.priceCalculate(
            item.flatsectionElectricity,
            item.elPrice
          );
          // 低谷
          item.valleysectionElectricity = dealElectricity(
            item?.valleysectionElectricity ?? 0,
            100,
            2
          );
          item.lowAll = this.priceCalculate(
            item.valleysectionElectricity,
            item.lowPrice
          );
          // 合计
          item.allquantity = dealElectricity(
            Number(item.spiksectionElectricity) +
              Number(item.peaksectionElectricity) +
              Number(item.flatsectionElectricity) +
              Number(item.valleysectionElectricity),
            1,
            2
          );
          if (
            item.peakAll == null &&
            item.highAll == null &&
            item.elAll == null &&
            item.lowAll == null
          ) {
            item.allmoney = null;
          } else {
            item.allmoney = dealElectricity(
              item?.peakAll ??
                0 + item?.highAll ??
                0 + item?.elAll ??
                0 + item?.lowAll ??
                0,
              1,
              2
            );
          }
        });
      }
    },
    // 电量处理金额计算
    priceCalculate(ele, price) {
      let result;
      if (price != null) {
        result = price * ele;
        result = dealElectricity(result);
      } else {
        result = null;
      }
      if (typeof result == "string") {
        result = Number(result);
      }
      return result;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
      // this.getPiedata();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        startAndend: null,
        deptId: null,
        // networksId: null,
        model: null,
        deviceCode: null,
        pageNum: 1,
        pageSize: 20,
      };
      this.extraParams = {};
      this.sysDeptIdChose = null;
      this.dictArr = [];
      this.getdeviceModel();
      this.handleQuery();
    },
    handlerSyschose(value) {
      // this.queryParams.networksId = null;
      let result;
      if (value && value.length > 0) {
        result = value[value.length - 1];
      } else {
        result = null;
      }
      this.sysDeptIdChose = result;
      this.extraParams = {
        sysDeptId: this.sysDeptIdChose,
      };
    },
    // choseNetwork(value) {
    //   // this.queryParams.networksId = value;
    // },
  },
};
</script>

<style scoped lang="scss">
.flexex {
  display: flex;
  // justify-content: space-between;
  justify-content: center;
  align-items: center;
  // padding: 0 20px;
  .el-icon-info {
    font-size: 18px;
    cursor: pointer;
    margin-left: 5px;
  }
}
</style>
